package com.erebus.utils;

import com.alibaba.fastjson.JSON;
import com.erebus.model.dto.TokenUser;
import com.nimbusds.jose.JWSVerifier;
import com.nimbusds.jose.Payload;
import com.nimbusds.jose.crypto.MACVerifier;
import com.nimbusds.jwt.SignedJWT;

import java.text.ParseException;
import java.util.Date;

public class JwtUtils {

    private static final String SECRET_KEY = "mis77mis77mis77mis77mis77mis7777";

    public static boolean validateToken(String token) throws ParseException {
        try {
            SignedJWT signedJWT = SignedJWT.parse(token);

            // 使用 MACVerifier 验证签名
            JWSVerifier verifier = new MACVerifier(SECRET_KEY.getBytes());
            boolean isSignatureValid = signedJWT.verify(verifier);

            if (!isSignatureValid) {
                return false;
            }

            // 手动验证是否过期
            Date expirationTime = signedJWT.getJWTClaimsSet().getExpirationTime();
            // 获取用户名
            String username = signedJWT.getJWTClaimsSet().getSubject();
            return expirationTime == null || new Date().before(expirationTime);
        } catch (Exception e) {
            return false;
        }
    }

    public static String extractUsername(String token) throws ParseException {
        return SignedJWT.parse(token).getJWTClaimsSet().getSubject();
    }

    // 解析token
    public static TokenUser parseToken(String token) throws ParseException {

        TokenUser tokenUser = null;
        SignedJWT parse = SignedJWT.parse(token);
        Payload payload = parse.getPayload();
        String string = payload.toString();
        try {
            tokenUser = JSON.parseObject(string, TokenUser.class);
        } catch (Exception e) {
            throw new RuntimeException("请求认证参数不符合要求");
        }

        return tokenUser;
    }
}